package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {

        //TODO 1、接口防刷

        //先从redis中取值，看是否过了60秒
        String s = redisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(s)) {
            String[] s1 = s.split("_");
            long l = Long.parseLong(s1[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60s内不能再发送验证码
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        //生成验证码
        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();

        //2、验证码的再次验证
        //①保存验证码至redis中。key-前缀+phone,value-验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //TODO 为了方便验证码是30天，注意修改
        ops.set(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + phone, code, 30, TimeUnit.DAYS);

        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * //TODO 分布式下 session问题
     * 注册方法
     *
     * @param vo
     * @param bindingResult
     * @param redirectAttributes 重定向时，request数据也携带
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {

        //校验出错则重定向到注册页
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            for (FieldError error : bindingResult.getFieldErrors()) {
                map.put(error.getField(), error.getDefaultMessage());
            }
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //真正注册。调用远程服务
        //1、检查验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            String[] s1 = s.split("_");
            if (StringUtils.equals(s1[0], vo.getCode())) {
                //验证通过，删除验证码
//                redisTemplate.delete(AuthServiceConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //真正注册->调用远程服务
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    //注册成功回到首页/登录页
                    return "http://auth.gulimall.com/login.html";
                } else {
                    //注册失败
                    Map<String, String> map = new HashMap<>();
                    map.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", map);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                //验证码不正确
                Map<String, String> map = new HashMap<>();
                map.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            //验证码不存在
            Map<String, String> map = new HashMap<>();
            map.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    /**
     * 登录
     *
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程调用->登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            //登录成功
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServiceConstant.LOGINUSER, data);
            return "redirect:http://gulimall.com";
        } else {
            //登录失败
            Map<String, String> map = new HashMap<>();
            map.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    /**
     * 去登陆页的逻辑
     * 如果已登录，就直接到首页；没有登录，才去登录页
     *
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServiceConstant.LOGINUSER);
        if (attribute != null) {
            //已登录
            return "redirect:http://gulimall.com";
        } else {
            //没登录
            return "login";
        }
    }

}
